package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Course;
import com.EAsystem.entity.Teacher;
import com.EAsystem.service.CourseService;
import com.EAsystem.service.TeacherService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class CourseController {

    @Autowired
    private CourseService courseService;
    
    @Autowired
    private TeacherService teacherService;

    /**
     * 课程信息管理页面，处理列表、搜索和分页
     */
    @GetMapping("/course")
    public String listCourses(@RequestParam(defaultValue = "1") int page,
                              @RequestParam(defaultValue = "5") int size,
                              Model model,
                              @RequestParam(required = false) String courseSearch) {
        
        PageInfo<Course> pageInfo;
        if (courseSearch != null && !courseSearch.trim().isEmpty()) {
            // 根据课程名称或者其他条件搜索
            Course searchCourse = new Course();
            searchCourse.setName(courseSearch.trim());
            pageInfo = courseService.findByConditionPageInfo(searchCourse, page, size);
        } else {
            pageInfo = courseService.findAllByPage(page, size);
        }

        if (pageInfo == null) {
            pageInfo = new PageInfo<>();
        }

        // 获取所有教师信息，用于新增/编辑模态框的下拉选择
        PageInfo<Teacher> teacherPageInfo = teacherService.findAllByPage(1, 1000); // 获取足够多的教师
        List<Teacher> teachersList = teacherPageInfo.getList();
        model.addAttribute("teachersList", teachersList);

        model.addAttribute("courses", pageInfo.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("courseSearch", courseSearch);

        return "admin/course";
    }

    /**
     * 新增课程
     */
    @PostMapping("/course/add")
    public String addCourse(Course course, @RequestParam(required = false) Integer teacherId) {
        if (teacherId != null) {
            Teacher teacher = teacherService.findById(teacherId);
            course.setTeacher(teacher);
        }
        // 设置课程状态，默认为1（启用）
        course.setStatus(1);
        courseService.save(course);
        return "redirect:/admin/course";
    }

    /**
     * 编辑课程
     */
    @PostMapping("/course/edit")
    public String editCourse(Course course, @RequestParam(required = false) Integer teacherId) {
        if (teacherId != null) {
            Teacher teacher = teacherService.findById(teacherId);
            course.setTeacher(teacher);
        }
        courseService.update(course);
        return "redirect:/admin/course";
    }

    /**
     * 删除单个课程
     */
    @GetMapping("/course/delete/{id}")
    public String deleteCourse(@PathVariable Long id) {
        courseService.delete(id);
        return "redirect:/admin/course";
    }

    /**
     * 批量删除课程
     */
    @GetMapping("/course/batchDelete")
    public String batchDeleteCourses(@RequestParam("ids") String ids) {
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids.split(",")) {
                try {
                    courseService.delete(Long.valueOf(id));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/admin/course";
    }

    /**
     * 获取单个课程信息（用于查看和编辑模态框填充）
     */
    @GetMapping("/course/view/{id}")
    @ResponseBody
    public Map<String, Object> viewCourse(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Course course = courseService.findById(id);
            if (course != null) {
                result.put("success", true);
                result.put("course", course);
            } else {
                result.put("success", false);
                result.put("message", "课程不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取课程信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新课程状态
     */
    @PostMapping("/course/updateStatus")
    @ResponseBody
    public Map<String, Object> updateCourseStatus(@RequestParam Long id, @RequestParam Integer status) {
        Map<String, Object> result = new HashMap<>();
        try {
            int updateResult = courseService.updateStatus(id, status);
            if (updateResult > 0) {
                result.put("success", true);
                result.put("message", "状态更新成功");
            } else {
                result.put("success", false);
                result.put("message", "状态更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "状态更新失败：" + e.getMessage());
        }
        return result;
    }
} 